var cheerio = require('cheerio');
var express = require('express');
var mysql = require('mysql');
var superagent = require('superagent');

var mysqlConfig = require('./config').mysqlConfig;

var list1 = [];
var connection1 = mysql.createConnection(mysqlConfig);
connection1.connect();
var query1 = 'select * from follow_list';
connection1.query(query1, function (err, res) {
    if (err) {
        console.log('err');
        console.log(err);
    } else {
        console.log('res');
        // console.log(res);
        list1 = res;
        update();
    }
});
connection1.end();

function update() {
    list1.forEach((v, i) => {
        var fundId = v['fund_id'];
        var url = 'http://fund.eastmoney.com/' + fundId + '.html';

        superagent.get(url).end(function (err, res) {
            if (err) {
                console.log('err');

            } else {
                console.log('res');
                var text = res.text;
                var $ = cheerio.load(text);

                var name = $('.funCur-FundName').first().text();
                console.log(name);

                var fundDetail_main = $('.fundDetail-main');
                var dataOfFund = fundDetail_main.find('.dataOfFund>dl');

                console.log(dataOfFund.length);

                // 单位净值
                var dwjz = Number(dataOfFund.eq(1).find('.dataNums>span').first().text());

                // 估算净值
                var gz_gsz = Number(dataOfFund.find('#gz_gsz').text());
                // 估算涨幅
                var gz_gszzl = dataOfFund.find('#gz_gszzl').text();
                var gz_gztime = dataOfFund.find('#gz_gztime').text();

                // console.log(gz_gszzl);


                // 单位净值

                var query2 = `update follow_list set  fund_name='${name}',dwjz=${dwjz}  where fund_id=${fundId}`;
                var connection2 = mysql.createConnection(mysqlConfig);
                connection2.connect();
                connection2.query(query2, function (err, res) {
                    if (err) {
                        console.log('err');
                        // console.log(err);

                    } else {
                        console.log('res');
                        console.log(res);

                    }
                });
                connection2.end();
            }
        })
    });
    setTimeout(() => {
        update();
    }, 60 * 1000);
}